﻿Imports LiteDB

Public Class Category
    Private mItems As List(Of CategoryItem)
#Region "Get Properties"
    Public ReadOnly Property CategoryList As List(Of CategoryItem)
        Get
            Return mItems
        End Get
    End Property
    Public ReadOnly Property GetCategory(CategoryID As Integer) As CategoryItem
        Get
            Return (From x In mItems Where x.CategoryID = CategoryID).First
        End Get
    End Property
#End Region
    Sub New()
        mItems = New List(Of CategoryItem)
        LoadList()
    End Sub
    Private Sub LoadList()
        Using db As New LiteEngine(gApp.DatabaseFile)
            mItems = (From x In db.GetCollection(Of CategoryItem)(DTCategories).All Order By x.CategoryDesc).ToList
            If mItems.Count = 0 Then AddCategory("Default")
        End Using
    End Sub
    Function Save(Data As CategoryItem) As Integer
        Dim tAdd As Boolean
        Dim tNewID As Integer
        Dim n As CategoryItem
        Using db As New LiteEngine(gApp.DatabaseFile)
            Dim col = db.GetCollection(Of CategoryItem)(DTCategories)

            tAdd = False
            If Data.CategoryID = 0 Then
                Try
                    tNewID = (From x In col.All Select x.CategoryID).Max + 1
                Catch ex As Exception
                    tNewID = 1
                End Try
                Data.CategoryID = tNewID
                tAdd = True
            End If

            If tAdd = True Then
                n = New CategoryItem
                n.CategoryID = Data.CategoryID
            Else
                n = col.FindById(Data.CategoryID)
                Dim a = (From x In mItems Where x.CategoryID = Data.CategoryID).First
                mItems.Remove(a)
            End If

            n.CategoryDesc = Data.CategoryDesc

            If tAdd = True Then
                col.Insert(n)
            Else
                col.Update(n)
            End If
            mItems.Add(n)
        End Using
        Return n.CategoryID
    End Function
    Public Sub AddCategory(Value As String)
        Dim a As New CategoryItem() With {.CategoryDesc = "Default"}
        Save(a)
    End Sub
End Class
